package com.blink.zookeeper.helloworld;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * <Description> </Description>
 * <ClassName> TestZookeeperConstructor</ClassName>
 *
 * @Author liuxianzhao
 * @Date 2018年01月12日 12:53
 */
public class TestZookeeperConstructor {
    private static final Logger logger = LoggerFactory.getLogger(TestZookeeperConstructor.class);

    @Test
    public void testZKConstructorUsageSimple() {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000,
                    new ZookeeperWatcher("zooKeeper", countDownLatch));
            countDownLatch.await();
        } catch (IOException | InterruptedException e) {
            logger.error("连接zookeeper发生异常", e);
            System.exit(0);
        }
//        zooKeeper.close();
    }

    @Test
    public void testZKConstructorUsageWithSidPasswd() throws IOException, InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zk = null;
        zk = new ZooKeeper("127.0.0.1:2181", 5000,
                new ZookeeperWatcher("zk", countDownLatch));
        countDownLatch.await();

        //使用非法的sessionId、sessionPasswd创建zookeeper连接
//        ZooKeeper illegalZk = new ZooKeeper("127.0.0.1:2181", 5000,
//                new ZookeeperWatcher("illegalZk", countDownLatch), 1L, "test".getBytes());
        //使用正确的sessionId、sessionPasswd创建zookeeper连接
        long sessionId = zk.getSessionId();
        byte[] sessionPasswd = zk.getSessionPasswd();
        ZooKeeper correctZk = new ZooKeeper("127.0.0.1:2181", 5000,
                new ZookeeperWatcher("correctZk", countDownLatch), sessionId, sessionPasswd);
        TimeUnit.MINUTES.sleep(1);
    }


    class ZookeeperWatcher implements Watcher {
        private String zkName;
        private CountDownLatch countDownLatch;

        public ZookeeperWatcher(String zkName, final CountDownLatch countDownLatch) {
            this.zkName = zkName;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void process(WatchedEvent watchedEvent) {
            logger.info("zkName:{},接收到事件：{}", zkName, watchedEvent);
            if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
                logger.info("zkName:{},连接到zookeeper", zkName);
                countDownLatch.countDown();
            }
        }
    }
}
